package forum_system_test;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author tongchen
 * @create 2023-08-18 15:09
 */
public class TestUtils {
    private static ChromeDriver chromeDriver = null;

    /**
     * 使用懒汉式创建ChromeDriver
     *
     * @return
     */
    public static ChromeDriver getDriver() {
        if (chromeDriver == null) {
            synchronized (TestUtils.class) {
                if (chromeDriver == null) {
                    //为避免后写后面的按钮无法加载导致报错，添加参数
                    ChromeOptions chromeOptions = new ChromeOptions();
                    chromeOptions.addArguments("headless") ;
                chromeDriver = new ChromeDriver();
                }
            }
        }

        return chromeDriver;
    }

    public static void getScreenShot() throws IOException {
        ChromeDriver driver = getDriver();
        //获取当前时间
        Date date = new Date();
        //获取当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
        String name = simpleDateFormat.format(date);
        String fileName = "./src/test/img" + name;
        //截图之前要等待全部元素加载完成
        driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
        File srcFile = driver.getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile, new File(fileName));

    }
}
